const path = require('path')
const fs = require('fs')
const dotEnv = require('dotenv')

// 修改public/env.development.js
const createEnvJs = () => {
  const mode = 'development'
  // 绝对路径
  const appDirectory = fs.realpathSync(process.cwd())

  const modeEnvPath = path.join(appDirectory, `.env.${mode}`)
  if (!fs.existsSync(modeEnvPath)) {
    console.log(`未找到.env.${mode}文件`)
    process.exit(1)
    return
  }
  const modeEnvBuffer = fs.readFileSync(modeEnvPath)
  const modeEnvConfig = dotEnv.parse(modeEnvBuffer)

  const envPath = path.join(appDirectory, '.env')
  let envConfig = {}
  if (fs.existsSync(envPath)) {
    const envBuffer = fs.readFileSync(envPath)
    envConfig = dotEnv.parse(envBuffer)
  }
  const config = {
    ...envConfig,
    ...modeEnvConfig
  }
  // 将内容写入到对应的js文件中
  const data = `window.env = ${JSON.stringify(config, null, 2)}`
  const publicPath = path.join(appDirectory, 'public')
  const devEnvPath = path.join(publicPath, 'env')
  if (!fs.existsSync(devEnvPath)) {
    fs.mkdirSync(devEnvPath)
  }
  fs.writeFileSync(path.join(devEnvPath, `env.${mode}.js`), data, 'utf-8')
}

createEnvJs()
